package org.teremail.panto;

import static java.lang.String.format;
import static org.teremail.panto.TestConstants.BODY_FORMAT;
import static org.teremail.panto.TestConstants.EPI_FORMAT;
import static org.teremail.panto.TestConstants.MULTI_FORMAT;
import static org.teremail.panto.TestConstants.PRE_FORMAT;

import java.io.IOException;
import java.io.InputStream;

import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.descriptor.BodyDescriptor;
import org.apache.james.mime4j.parser.Field;


public class Mime4JContentHandler implements org.apache.james.mime4j.parser.ContentHandler {
    
    StringBuilder sb = new StringBuilder();

    public void body(BodyDescriptor bd, InputStream in) throws IOException {
        //IOUtil.dump("mime4j.text", in);
        sb.append(format(BODY_FORMAT, bd.getMimeType(), IOUtil.count(in)));
    }
    
    public void startMultipart(BodyDescriptor arg0) {
        String t = arg0.getMimeType();
        String b = arg0.getBoundary();
        sb.append(format(MULTI_FORMAT, t, b));
    }
    
    public String toString() {
        return sb.toString();
    }

    public void endBodyPart() {
        sb.append("};");
    }

    public void endHeader() {
        sb.append("];");
    }

    public void endMessage() {
        sb.append("};");
    }

    public void endMultipart() {
        sb.append("};");
    }

    public void epilogue(InputStream in) throws IOException {
        sb.append(format(EPI_FORMAT, IOUtil.count(in)));
    }

    @Override
    public void field(Field field) throws MimeException {
        System.out.println("Field: " + field);
        //sb.append(">");
        sb.append(field);
        sb.append(";");
    }

    public void field(String s) {
        System.out.println("Field: " + s);
        //sb.append(">");
        sb.append(s);
        sb.append(";");
    }

    public void preamble(InputStream in) throws IOException {
        sb.append(format(PRE_FORMAT, IOUtil.count(in)));
    }

    public void raw(InputStream arg0) throws IOException {
    }

    public void startBodyPart() {
        sb.append("bodyPart:{");
    }

    public void startHeader() {
        sb.append("header:[");
    }

    public void startMessage() {
        sb.append("message:{");
    }


}
